var EventEmitter = require('events').EventEmitter;
var i18n = require('./js/i18n');
var Shotenjin = require('./js/lib/shotenjin');

function buildStatusHtmlok() {
    var htmls = [];
    var c_user = [];
    c_user.t_url="abc";
    c_user.profile_image_url="hhhhhhhhhhhhh";

    var context = {
        test_moban_val: 1,
        user: c_user
    };
    try {
        var html = Shotenjin.render(window.TEST_MOBAN, context);
        htmls.push(html);
    } catch (err) {
        // throw err;
        console.error(err);
    }
    return htmls;
}

// status content
function TextContentController() {
    // status content
    this.$textContent = $('#txtContent');
    this.$textContent.on('keydown', {
        controller: this,
        action: this.send.bind(this),
        close: function () {
            $('#show_status_input').click();
        }
    }, this.keypress)
        .on('input focus', { controller: this }, this.count);
    this.$textContent[0].onpaste = this.paste;

    $('#btnSend').click(this.send.bind(this));
    $('#btnClearText').click(this.clearText.bind(this));
    $('#show_status_input').on('click', { controller: this }, this.toggleTextInput);
    $('#fileDialog').on('change', { controller: this }, this.fileChange);

    // reply
    this.$replyText = $('#replyTextarea');

    this.$replyText.on('keydown', {
        controller: this,
        action: this.sendReply.bind(this),
        close: function () {
            $('.close_dialog:first').click();
        }
    }, this.keypress).on('input focus', { controller: this }, this.count);

    $('#replySubmit').click(this.sendReply.bind(this));
    $('.close_dialog').click({ controller: this }, this.hideReply);
    this.$replyText[0].onpaste = this.pasteOnReply;

    at_user_autocomplete('#txtContent');
    at_user_autocomplete('#replyTextarea');

    this.loadStates();
}

TextContentController.prototype.fileChange = function (event) {
    var files = $(this).prop('files') || [];
    if (files.length === 0) {
        return;
    }
    var file = files[0];
    readImage(file, function (image) {
        window.imgForUpload = file;
        window.imgForUpload.fileName = 'fawave.png';
        _init_image_preview(image, file.size, 'upImgPreview', 'btnUploadPic');
    });
};

TextContentController.prototype.hideReply = function (event) {
    var self = event.data.controller;
    self.$replyText.blur();
    var dialog = $('#ye_dialog_window');
    $('#btnFaceBoxClose').click();
    dialog.hide();
    dialog.find('input[type="hidden"], input[type="checkbox"], textarea').val('');
    window.imgForUpload_reply = null;
    $('#upImgPreview_reply').hide().find('.img').html('');
    // 隐藏带上原评论选项
    $('#chk_originalComment, #txt_originalComment').hide();
    // cleanActionCache();
};

TextContentController.prototype.loadStates = function () {
    var unsendText = localStorage.getObject(CONST.UNSEND_TWEET_KEY);
    if (unsendText) {
        this.$textContent.val(unsendText);
    }

    var unsendReply = localStorage.getObject(CONST.UNSEND_REPLY_KEY);
    if (unsendReply) {
        this.$replyText.val(unsendReply);
    }
};

TextContentController.prototype.paste = function (event) {
    _get_clipboard_file(event, function (file, image) {
        if (file) {
            window.imgForUpload = file;
            window.imgForUpload.fileName = 'fawave.png';
            _init_image_preview(image, file.size, 'upImgPreview', 'btnUploadPic');
        }
    });
};

TextContentController.prototype.pasteOnReply = function (event) {
    _get_clipboard_file(event, function (file, image) {
        if (file) {
            window.imgForUpload_reply = file;
            window.imgForUpload_reply.fileName = 'fawave_reply.png';
            _init_image_preview(image, file.size, 'upImgPreview_reply', 'btnAddReplyEmotional', 60);
        }
    });
};

TextContentController.prototype.toggleTextInput = function (event) {
    var self = event.data.controller;
    var preview = $("#upImgPreview");
    if ($("#submitWarp").data('status') !== 'show') {
        self.showTextInput();
        if (window.imgForUpload) {
            setTimeout(function () {
                preview.show();
            }, 500);
        }
        return;
    }
    preview.hide();
    self.hideTextInput();
};

TextContentController.prototype.showTextInput = function () {
    var $submitWarp = $('#submitWarp');
    if ($submitWarp.data('status') !== 'show') {
        initSelectSendAccounts();
        var h_submitWrap = $submitWarp.find(".w").height();
        var h = window.innerHeight - 70 - h_submitWrap;
        $('.list_warp').css('height', h);
        $submitWarp.data('status', 'show').css('height', h_submitWrap);
        $('#header .write').addClass('active').find('b').addClass('up');
        $('#doing').appendTo('#doingWarp');
        // ActionCache.set('showMsgInput', []);
    }
    var value = this.$textContent.val();
    this.$textContent.focus().val('').val(value); //光标在最后面
};

TextContentController.prototype.hideTextInput = function () {
    $('#btnFaceBoxClose').click();
    var h = window.innerHeight - 70;
    $(".list_warp").css('height', h);
    $("#submitWarp").data('status', 'hide').css('height', 0);
    $("#header .write").removeClass('active').find('b').removeClass('up');
    $("#doing").prependTo('#tl_tabs .btns');
    this.$textContent.blur(); // 让它失去焦点，避免快捷键被输入了
    // ActionCache.set('showMsgInput', null);
};

TextContentController.prototype.send = function () {
    var text = this.$textContent.val().trim();
    if (!text) {
        showMsg(i18n.get("msg_need_content"));
    }
    sendMsg(text);
};

TextContentController.prototype.sendReply = function () {
    sendMsgByActionType(this.$replyText.val().trim());
};

TextContentController.prototype.clearText = function () {
    this.$textContent.val('').focus();
};

TextContentController.prototype.keypress = function (event) {
    // ctrl + enter || cmd + enter || alt + s
    if (((event.ctrlKey || event.metaKey) && event.keyCode === 13) || (event.altKey && event.which === 83)) {
        event.data.action();
        return false;
    }
};

TextContentController.prototype.count = function (event) {
    var input = $(this);
    var parent = input.parent();
    var value = input.val();
    var max_length = parseInt(input.data('max_text_length'), 10) || 140;
    var len = max_length - (input.data('support_double_char') ? value.len() : value.length);
    // return [value, len, max_length];
    var sendBtn = parent.find('.send');
    var wlength = max_length - value.len();
    if (len === max_length) {
        sendBtn.attr('disabled', 'disabled');
    } else {
        sendBtn.removeAttr('disabled');
    }
    parent.find('.wordCount_double').html(wlength);
    parent.find('.wordCount').html(len);
};


$(function () {
    //resizeWindow();
    //$(window).resize(resizeWindow);

    console.log('controllers init...');

    new TextContentController();
    console.log('controllers inited.');

});